package com.mybatis.criteria;

import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;

public abstract class MyCriteria implements Serializable {

    public static final String DEFAULT_PARAM_ALIAS = "ec";
    /**
     * 占位符
     */
    private static final String PLACE_HOLDER = "{%s}";
    private static final String MYBATIS_PLUS_TOKEN = "#{%s.%s}";
    private static final String MP_GENERAL_PARAMNAME = "paramName";

    protected transient SqlBuilder sql = new SqlBuilder();
    private transient Map<String, Object> paramNameValuePairs = new TreeMap<>();
    private AtomicInteger paramNameSeq = new AtomicInteger(0);
    private Boolean isContain;

    protected MyCriteria(Boolean isContain) {
        this.isContain = isContain;
    }

    public Boolean getContain() {
        return isContain;
    }

    public Map<String, Object> getParamNameValuePairs() {
        return paramNameValuePairs;
    }

    public void setParamNameValuePairs(Map<String, Object> paramNameValuePairs) {
        this.paramNameValuePairs = paramNameValuePairs;
    }

    public abstract String getSqlSegment();

    @Override
    public String toString() {
        String sqlSegment = getSqlSegment();
        if (!StringUtils.isEmpty(sqlSegment)) {
            sqlSegment = sqlSegment.replaceAll("#\\{" + DEFAULT_PARAM_ALIAS + "." + MP_GENERAL_PARAMNAME + "[0-9]+\\}", "\\?");
        }
        return sqlSegment;
    }

    public MyCriteria eq(String column, Object params) {
        sql.where(formatSql(String.format("%s = {0}", column), params));
        return this;
    }

    public MyCriteria or() {
        sql.or();
        return this;
    }

    protected  String formatSql(String sqlStr, Object params)
    {
        if (params != null ) {
                String genParamName = MP_GENERAL_PARAMNAME +String.format("%03d",paramNameSeq.incrementAndGet()) ;
                sqlStr = sqlStr.replace(String.format(PLACE_HOLDER, 0),
                        String.format(MYBATIS_PLUS_TOKEN, DEFAULT_PARAM_ALIAS, genParamName));
                paramNameValuePairs.put(genParamName, params);
        }
        return sqlStr;
    }

}
